<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage, ElTag } from 'element-plus'
import { FormSchema } from '@/components/Form'
import { Table, TableColumn } from '@/components/Table'
import {
  getDepartmentTableApi,
  createDepartmentApi,
  updateDepartmentApi,
  deleteDepartmentApi
} from '@/api/department'
import { DepartmentItem, DepartmentSaveData } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive, computed } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { BaseButton } from '@/components/Button'
import { listToTree } from '@/utils/tree'
import { CalculateCellWidth } from '@/utils/calculateCellWidth'

const { t } = useI18n()

const ids = ref<number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const { data, pagination } = await getDepartmentTableApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: listToTree(data, { pid: 'parentDeptId' }),
      total: pagination?.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDepartmentApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const actionWidth = computed(() =>
  CalculateCellWidth([
    { permission: 'department:update', width: 86 },
    { permission: 'department:detail', width: 86 },
    { permission: 'department:delete', width: 86 }
  ])
)

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    label: t('common.tableIndex'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('department.name'),
    slots: {
      default: (data: any) => {
        return <>{data.row.name}</>
      }
    }
  },
  {
    field: 'status',
    label: t('department.status'),
    slots: {
      default: (data: any) => {
        const status = data.row.status
        return (
          <>
            <ElTag type={status ? 'success' : 'danger'}>
              {status ? t('common.enable') : t('common.disable')}
            </ElTag>
          </>
        )
      }
    }
  },
  {
    field: 'createdAt',
    label: t('common.createTime')
  },
  {
    field: 'remark',
    label: t('common.remark')
  },
  {
    field: 'action',
    label: t('common.action'),
    width: actionWidth.value,
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton
              type="primary"
              v-prem={{ value: 'department:update' }}
              onClick={() => action(data.row, 'edit')}
            >
              {t('common.edit')}
            </BaseButton>
            <BaseButton
              type="success"
              v-prem={{ value: 'department:detail' }}
              onClick={() => action(data.row, 'detail')}
            >
              {t('common.detail')}
            </BaseButton>
            <BaseButton
              type="danger"
              v-prem={{ value: 'department:delete' }}
              onClick={() => delData(data.row)}
            >
              {t('common.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('department.name'),
    component: 'Input'
  }
])
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentId = ref<number | null>(null)
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const action = (row: DepartmentItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentId.value = row.id
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('common.add')
  currentId.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: DepartmentItem | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: DepartmentItem) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (!formData) return ElMessage.error('请填写完整')
  saveLoading.value = true
  const res = await (
    actionType.value === 'add'
      ? createDepartmentApi(formData as DepartmentSaveData)
      : updateDepartmentApi(formData as DepartmentSaveData)
  )
    .catch(() => {})
    .finally(() => {
      saveLoading.value = false
    })
  if (res) {
    dialogVisible.value = false
    currentPage.value = 1
    await getList()
  }
}
</script>

<template>
  <ContentWrap v-prem="'department:page'">
    <Search :schema="searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" v-prem="'department:create'" @click="AddAction">
        {{ t('common.add') }}
      </BaseButton>
      <BaseButton
        :loading="delLoading"
        type="danger"
        v-prem="'department:delete'"
        @click="delData(null)"
      >
        {{ t('common.batchDelete') }}
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-id="currentId || 0" />

    <Detail v-if="actionType === 'detail'" :current-id="currentId || 0" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('common.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('common.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
